import { useCallback, useState, useEffect, useRef } from "react";
import { useDispatchUser } from "@/hooks/user";
import { LoginData } from "@/types/userType";
import {Form, Input, Button, Field, Cell, Toast, Image, Flex, Navbar} from "@taroify/core";
import { BaseEventOrig, FormProps, View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import {ArrowLeft, EyeOutlined} from "@taroify/icons";
import appIcon from '@/assets/images/virtual_teacher_icon.png'
import './index.css';


function Login() {
  const windowInfo = Taro.getWindowInfo();
  const statusBarHeight = windowInfo.statusBarHeight;
  const [btnLoad, setBtnLoad] = useState(false);
  const [passwordVisible, setPasswordVisible] = useState(false);
  const { login, getCaptcha } = useDispatchUser();
  const hasFetchedCaptcha = useRef(false);

  // 刷新验证码
  const refreshCaptcha = useCallback(() => {
    getCaptcha();
  }, [getCaptcha]);

  // 初始化时获取验证码
  useEffect(() => {
    if (!hasFetchedCaptcha.current) {
      refreshCaptcha();
      hasFetchedCaptcha.current = true;
    }
  }, [refreshCaptcha]);

  // 切换密码可见性
  const togglePasswordVisibility = () => {
    setPasswordVisible(!passwordVisible);
  };

  // 表单提交
  const onSubmit = async (event: BaseEventOrig<FormProps.onSubmitEventDetail>) => {
    try {
      const values = event.detail.value as LoginData;
      values.captcha = 'abcd'; // 模拟验证码
      setBtnLoad(true); // 设置按钮加载状态

      // 调用登录接口
      await login(values);

      // 显示成功提示
      await Taro.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 2000,
      });

      // 跳转到对话页面
      await Taro.redirectTo({
        url: '/pages/tabs/dialogue/index',
      });
    } catch (error) {
      // 显示失败提示
      await Taro.showToast({
        title: error.message || '登录失败',
        icon: 'error',
        duration: 2000,
      });
    } finally {
      // 重置按钮加载状态
      setBtnLoad(false);
    }
  };

  const handleRegister = async () => {
    await Taro.redirectTo({
      url: '/pages/auth/register/index', // 跳转到注册页面
    });
  }

  const handleWxLogin = async () => {
    await Taro.redirectTo({
      url: '/pages/auth/register/index', // 跳转到注册页面
    });
  }

  const handleBackHome = async ()=> {
    await Taro.redirectTo({
      url: '/pages/tabs/dialogue/index',
    });
  }


  return (
    <View style={{height: '100vh', width: '100wv', background: 'linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%)'}}>
      <Navbar
        fixed
        style={{
          paddingTop: `${(statusBarHeight || 0) + 50}rpx`,
          boxShadow: '0 2rpx 10rpx rgba(0, 0, 0, 0.1)',
        }}
      >
        <Navbar.NavLeft icon={<ArrowLeft onClick={handleBackHome} size={25} color='black' />} />
        <Navbar.Title style={{ fontSize: '35rpx', color: 'black' }}>登录</Navbar.Title>
      </Navbar>
      <Flex justify='center' align='center' direction='column' style={{height: '100%', width: '100%'}}>
        <View>
          <Image
            src={appIcon}
            style={{width: '300rpx', height: '300rpx',}}
          />
        </View>
        <Form onSubmit={onSubmit}>
          <Toast id='toast' />
          <Cell.Group inset>
            {/* 用户名 */}
            <Field
              label='用户名'
              name='username'
              rules={[{ required: true, message: "请填写用户名" }]}
            >
              <Input
                type='nickname'
                className='info-content__input'
                placeholder='请输入昵称'
              />
            </Field>

            {/* 密码 */}
            <Field
              label='密码'
              name='password'
              rules={[{ required: true, message: "请填写密码" }]}
              rightIcon={passwordVisible ? (
                <EyeOutlined
                  onClick={togglePasswordVisibility}
                  style={{ cursor: 'pointer', color: 'inherit' }}
                />
              ) : (
                <EyeOutlined
                  onClick={togglePasswordVisibility}
                  style={{ cursor: 'pointer', color: 'inherit' }}
                />
              )}
            >
              <Input placeholder='请输入密码' />
            </Field>

            <Cell>
              <Text>还未有账号，前去</Text><Text onClick={handleRegister} style={{cursor: 'pointer', color: 'blue'}}>注册</Text>
            </Cell>
            <Cell>
              <Text>微信一键</Text><Text onClick={handleWxLogin} style={{cursor: 'pointer', color: 'blue'}}>登录</Text>
            </Cell>
          </Cell.Group>

          {/* 提交按钮 */}
          <View style={{ margin: '16px' }}>
            <Button
              openType='getUserInfo|agreePrivacyAuthorization'
              shape='round'
              block
              color='primary'
              // formType='submit'
              loading={btnLoad}
            >
              登录
            </Button>
          </View>
        </Form>
      </Flex>
    </View>
  );
}

export default Login;
